<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 300px;
            height: 300px;
            background-color: lavender;
            position: absolute;
            left: 0;
        }
    </style>
</head>

<body>
    <button>移动到400px</button>
    <button>移动到800px</button>
    <button>返回为0px</button>
    <div></div>
</body>
<script>
    let btnList = document.getElementsByTagName('button');
    let div = document.querySelector('div');
    btnList[0].onclick = function () {
        animation(div, 400)
    }
    btnList[1].onclick = function () {
        animation(div, 800)
    }
    btnList[2].onclick = function () {
        animation(div, 0)
    }

    function animation(element, target) {
        clearInterval(element.times)
        let current = element.offsetLeft;
        console.log(current);
        let step = 10;
        step = current <= target ? step : -step;
        element.times = setInterval(function () {
            if (Math.abs(current - target) <= Math.abs(step)) {
                element.style.left = target + 'px';
                clearInterval(element.times);
            } else {
                current += step;
                element.style.left = current + 'px';
            }

        }, 50)
    }
</script>

</html>